package mvc.controller.filter;

import com.google.gson.Gson;
import mvc.model.pojos.AddressBean;
import mvc.model.pojos.UserBean;
import mvc.model.service.AddressService;
import mvc.model.service.UserService;
import mvc.model.service.impl.AddressServiceImpl;
import mvc.model.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
import java.util.List;

@WebFilter(filterName = "BFilter", urlPatterns = "/*")

public class BFilter implements Filter {
    private static String charset;
    static {
        charset = "utf-8";
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //设置中文
        request.setCharacterEncoding(charset);
        response.setCharacterEncoding(charset);

        String path = request.getRequestURI();
        System.out.println(path);

        if (request.getSession().getAttribute("user") == null) {
            cg(request);
        }
        if (request.getSession().getAttribute("user") != null) {
            UserBean userBean = (UserBean) request.getSession().getAttribute("user");
            AddressService addressService = new AddressServiceImpl();
            List<AddressBean> select = addressService.select(userBean.getUid(), 1);
            request.getSession().setAttribute("addrList", select);
        }
        if (path.endsWith(".jsp")) {
//            cg(request);
            request.getRequestDispatcher("WEB-INF/jsp" + path).forward(request, response);
            return;
        }
        chain.doFilter(request, response);
    }

    public void init(FilterConfig config) throws ServletException {

    }

    private void cg(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || !(cookies.length > 0)) {
            return;
        }
        String uname = null;
        String upass = null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("uname")) {
                uname = cookie.getValue();
            }
            if (cookie.getName().equals("upass")) {
                upass = cookie.getValue();
            }
        }
        if (uname == null || upass == null) {
            return;
        }
        UserService service = new UserServiceImpl();
        UserBean login = service.login(uname, upass);
        if (login != null) {
            request.getSession().setAttribute("user", login);
        }

    }

}
